package com.xc.freeapp.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xc.freeapp.dao.UsersDao;
import com.xc.freeapp.dao.dataSource.DBContextHolder;

import com.xc.freeapp.entity.Users;
import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.service.UsersService;
import com.xc.freeapp.util.Constant;
import com.xc.freeapp.util.DateUtils;

/**
 * 
 * @author wukailuo
 * 
 */
@Service
public class UsersServiceImpl implements UsersService{
	Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private UsersDao usersdao;
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public Users login(String telephone, String loginPwd,String businessid) {
		DBContextHolder.switchDataSourceRW();//切换数据源
		Users  users=new  Users();
		users.setTelephone(telephone);
		users.setLoginpwd(loginPwd);
		users.setBusinessid(Integer.parseInt(businessid));
        Users user=usersdao.login(users);
		return  user;
	}

	/**
	 * 个人详情查询
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public Users getUserInfo(String usersid) {
		DBContextHolder.switchDataSourceRW();//切换数据源
		return usersdao.getUserInfo(usersid);
	}
	
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public int updateUserInfo(Map<String ,String> map) throws BaseException  {
		DBContextHolder.switchDataSourceRW();//切换数据源
		Users   user=usersdao.getUserInfo(map.get("userId"));
		String updateType = map.get("updatetype");
		String updatevalue = map.get("updatevalue");
		if("1".equals(updateType)){
			user.setLoginpwd(updatevalue);
		}else if("2".equals(updateType)){
			user.setQqnum(updatevalue);
		}else if("3".equals(updateType)){
			user.setEmail(updatevalue);
		}
		user.setUpdatetime(DateUtils.getDate());
		int value = usersdao.updateByPrimaryKeySelective(user);
		
		
		return value;
	}

	public int updateuserinfo(Users users) throws BaseException {
		DBContextHolder.switchDataSourceRW();//切换数据源
		int result=0;
		try{
 			result=usersdao.updateByPrimaryKeySelective(users);
		}catch(DuplicateKeyException e){
			log.error(users.getTelephone()+"该号码已经注册");
			throw new BaseException(Constant.ERRORCODE_106);
		}
		return result;
	}
	
	public int selectCount(Map<String, String> paramsmap) {
		DBContextHolder.switchDataSourceRW();//切换数据源
		return usersdao.selectifhave(paramsmap);
	}
	
}
